#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import logging
import json
import aiohttp_jinja2
from aiohttp import web

from . import db
from .coreweb import query_string, post_params

routes = web.RouteTableDef()
module_name = 'database'


@routes.get('/%s' % module_name)
# @aiohttp_jinja2.template('database.html')
async def database(request):
    data = {}
    data = dict(data, **request.app['view_commons'])
    return {'data': data, '__template__': 'database.html'}


@routes.post('/%s/execute' % module_name)
async def execute_sql(request):
    params = await request.json()
    sql = params.get(
        'sql', "SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1")
    logging.info(sql)
    if sql is None or len(sql) <= 0:
        logging.error('sql 为空";": %s' % (sql))
        return {'code': -1, 'msg': 'sql 为空";": %s' % (sql)}
    if ';' not in sql:
        logging.error('sql 中不包含";": %s' % (sql))
        return {'code': -1, 'msg': 'sql 中不包含";": %s' % (sql)}
    result = db.execute_sql(sql)
    if result['status']:
        return {'code': 0, 'msg': json.dumps(result['msg'], ensure_ascii=False)}
    logging.error('failed to execute_sql: %s\n%s' % (sql, result['msg']))
    return {'code': -1, 'msg': 'failed to execute_sql: %s\n%s' % (sql, result['msg'])}


@routes.post('/%s/test' % module_name)
async def testpost(request):
    params = await post_params(request)
    print('-' * 65)
    print('parmas: %s' % params)
    print('-' * 65)
    return {'code': 0, 'msg': 'Ok!'}
